<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item
        label="商品分类"
        prop="goodsType"
      >
        <el-select
          v-model="queryParams.goodsType"
          placeholder="请选择商品分类"
          clearable
          style="width: 240px"
        >
          <el-option
            label="男装"
            value="男装"
          />
          <el-option
            label="女装"
            value="女装"
          />
          <el-option
            label="童装"
            value="童装"
          />
          <el-option
            label="运动装"
            value="运动装"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="文案说明"
        prop="goodsContent"
      >
        <el-input
          v-model="queryParams.goodsContent"
          placeholder="请输入文案说明"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
      >
        <el-select
          v-model="queryParams.status"
          placeholder="商品状态"
          clearable
          style="width: 240px"
        >
          <el-option
            label="正常"
            value="0"
          />
          <el-option
            label="关闭"
            value="1"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="Refresh"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="商品ID"
        prop="id"
        width="80"
      />
      <el-table-column
        label="商品名称"
        prop="goodsName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="商品分类"
        prop="goodsType"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="文案说明"
        prop="goodsContent"
        :show-overflow-tooltip="true"
        width="200"
      />
      <el-table-column
        label="价格(元)"
        prop="goodsMoney"
        width="100"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.goodsMoney || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        width="100"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            :disabled="loading"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        prop="goodsPic"
        width="100"
        align="center"
      >
        <template #default="scope">
          <el-image
            v-if="scope.row.goodsPic"
            :src="scope.row.goodsPic"
            :preview-src-list="[scope.row.goodsPic]"
            fit="cover"
            style="width: 50px; height: 50px"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template #default="scope">
          <el-tooltip
            content="修改"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
    >
      <el-form
        ref="goodsRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="商品名称"
              prop="goodsName"
            >
              <el-input
                v-model="form.goodsName"
                placeholder="请输入商品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="商品分类"
              prop="goodsType"
            >
              <el-select
                v-model="form.goodsType"
                placeholder="请选择商品分类"
                style="width: 100%"
              >
                <el-option
                  label="男装"
                  value="男装"
                />
                <el-option
                  label="女装"
                  value="女装"
                />
                <el-option
                  label="童装"
                  value="童装"
                />
                <el-option
                  label="运动装"
                  value="运动装"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="价格(元)"
              prop="goodsMoney"
            >
              <el-input-number
                v-model="form.goodsMoney"
                :precision="2"
                :min="0"
                :max="999999"
                style="width: 100%"
                placeholder="请输入商品价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="文案说明"
          prop="goodsContent"
        >
          <el-input
            v-model="form.goodsContent"
            type="textarea"
            :rows="4"
            placeholder="请输入文案说明"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="图片地址"
          prop="goodsPic"
        >
          <el-input
            v-model="form.goodsPic"
            placeholder="请输入图片地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
          >确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductType">
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  exportGoods
} from '@/api/type-config/goods'
import { parseTime } from '@/utils/ruoyi'
import { nextTick } from 'vue'

const { proxy } = getCurrentInstance()

const goodsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dataInitialized = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsType: undefined,
    goodsContent: undefined,
    status: undefined
  },
  rules: {
    goodsName: [
      { required: true, message: '商品名称不能为空', trigger: 'blur' }
    ],
    goodsType: [
      { required: true, message: '商品分类不能为空', trigger: 'change' }
    ],
    goodsContent: [
      { required: true, message: '文案说明不能为空', trigger: 'blur' }
    ],
    goodsMoney: [
      { required: true, message: '商品价格不能为空', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商品列表 */
function getList() {
  loading.value = true
  dataInitialized.value = false
  listGoods(queryParams.value)
    .then((response) => {
      goodsList.value = response.rows || []
      total.value = response.total || 0
      loading.value = false
      // 延迟设置初始化完成标志，确保DOM更新完成
      nextTick(() => {
        setTimeout(() => {
          dataInitialized.value = true
        }, 100)
      })
    })
    .catch(() => {
      loading.value = false
      dataInitialized.value = true
    })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const goodsIds = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除商品编号为"' + goodsIds + '"的数据项?')
    .then(function () {
      return delGoods(goodsIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/goods/export',
    {
      ...queryParams.value
    },
    `goods_${new Date().getTime()}.xlsx`
  )
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 商品状态修改 */
function handleStatusChange(row) {
  // 如果数据还没有初始化完成，不处理状态变更
  if (!dataInitialized.value) {
    return
  }

  let text = row.status === '0' ? '启用' : '停用'
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.goodsName + '"吗?')
    .then(function () {
      return updateGoods(row)
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}

/** 重置表单 */
function reset() {
  form.value = {
    id: undefined,
    goodsName: undefined,
    goodsType: undefined,
    goodsContent: undefined,
    status: '0',
    goodsMoney: undefined,
    goodsPic: undefined,
    remark: undefined
  }
  proxy.resetForm('goodsRef')
}

/** 添加商品 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加商品'
}

/** 修改商品 */
function handleUpdate(row) {
  reset()
  const goodsId = row.id || ids.value
  getGoods(goodsId).then((response) => {
    form.value = response.data || response
    open.value = true
    title.value = '修改商品'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['goodsRef'].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

getList()
</script>
